class Solution(object):
    def findAndReplacePattern(self, words, pattern):
        """
        :type words: List[str]
        :type pattern: str
        :rtype: List[str]
        """
        n = len(pattern)
        out = []
        for word in words:
            a_set = set()
            b_list = {}
            flag = True
            for i in range(n):
                if pattern[i] in b_list:
                    if b_list[pattern[i]] != word[i]:
                        flag = False
                        break
                else:
                    if word[i] in a_set:
                        flag = False
                        break
                    else:
                        b_list[pattern[i]] = word[i]
                        a_set.add(word[i])
            if flag:
                out.append(word)
        return out
